package com.mazewei.dev.service;

import com.mazewei.dev.dao.TeacherDao;
import com.mazewei.dev.entity.Teacher;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * 教师匹配服务
 * 负责处理教师姓名的匹配、格式化和编号生成
 */
@Service
public class TeacherMatchingService {
    
    private static final Logger logger = LoggerFactory.getLogger(TeacherMatchingService.class);
    
    @Autowired
    private TeacherDao teacherDao;
    
    /**
     * 获取教师编号（从数据库查询）
     * @param teacherName 教师姓名
     * @return 教师编号
     */
    public String getTeacherCode(String teacherName) {
        if (teacherName == null || teacherName.trim().isEmpty()) {
            logger.warn("[教师匹配失败] 教师姓名为空");
            return "";
        }
        
        logger.info("[教师匹配开始] 教师姓名: {}", teacherName);
        
        try {
            // 步骤1: 尝试直接匹配原始教师姓名
            logger.debug("[步骤1] 尝试原始教师姓名查找: {}", teacherName);
            Teacher teacher = teacherDao.findByFullName(teacherName);
            if (teacher != null && teacher.getTrNum() != null) {
                logger.info("[教师匹配成功] 原始姓名匹配 - 教师: {} -> 编号: {}", teacherName, teacher.getTrNum());
                return teacher.getTrNum();
            }
            //清除教师名称后面的干扰
            String cleanedName = removeNumbersFromTeacherName(teacherName);
            if (!cleanedName.equals(teacherName)) {
                logger.debug("[步骤2] 尝试清理数字后的教师姓名查找: {} -> {}", teacherName, cleanedName);
                teacher = teacherDao.findByFullName(cleanedName);
                if (teacher != null && teacher.getTrNum() != null) {
                    logger.info("[教师匹配成功] 清理数字后姓名匹配 - 教师: {} -> 编号: {}", cleanedName, teacher.getTrNum());
                    return teacher.getTrNum();
                }
            }
            
            // 步骤3: 尝试其他可能的姓名变体
            List<String> possibleNames = generatePossibleTeacherNames(teacherName);
            for (String possibleName : possibleNames) {
                logger.debug("[步骤3] 尝试可能的教师姓名: {}", possibleName);
                teacher = teacherDao.findByFullName(possibleName);
                if (teacher != null && teacher.getTrNum() != null) {
                    logger.info("[教师匹配成功] 可能姓名匹配 - 教师: {} -> 编号: {}", possibleName, teacher.getTrNum());
                    return teacher.getTrNum();
                }
            }
            
            // 步骤4: 如果所有匹配都失败，返回空字符串而不是生成默认编号
            logger.error("[教师匹配失败] 数据库中未找到教师: {}", teacherName);
            return ""; // 修改：返回空字符串而不是生成默认编号
            
        } catch (Exception e) {
            logger.error("[教师匹配异常] 查询教师编号时发生错误: {}", teacherName, e);
            return ""; // 修改：返回空字符串而不是生成默认编号
        }
    }
    
    /**
     * 移除教师姓名末尾的数字
     * @param teacherName 原始教师姓名
     * @return 移除数字后的教师姓名
     */
    public String removeNumbersFromTeacherName(String teacherName) {
        if (teacherName == null || teacherName.trim().isEmpty()) {
            return teacherName;
        }
        
        try {
            // 移除姓名末尾的数字（通常用于区分同名教师）
            String cleanedName = teacherName.replaceAll("\\d+$", "").trim();
            
            if (!cleanedName.equals(teacherName)) {
                logger.debug("[教师姓名清理] {} -> {}", teacherName, cleanedName);
            }
            
            return cleanedName;
            
        } catch (Exception e) {
            logger.error("[教师姓名清理异常] 清理教师姓名时发生错误: {}", teacherName, e);
            return teacherName;
        }
    }
    
    /**
     * 生成可能的教师姓名变体
     * @param teacherName 原始教师姓名
     * @return 可能的教师姓名列表
     */
    private List<String> generatePossibleTeacherNames(String teacherName) {
        List<String> possibleNames = new ArrayList<>();
        
        if (teacherName == null || teacherName.trim().isEmpty()) {
            return possibleNames;
        }
        
        String originalName = teacherName.trim();
        
        //  尝试移除所有数字和特殊字符
        String alphaOnly = originalName.replaceAll("[^\u4e00-\u9fa5a-zA-Z]", "");
        if (!alphaOnly.equals(originalName)) {
            possibleNames.add(alphaOnly);
        }
        
        //  尝试移除空格
        String noSpaces = originalName.replace(" ", "").replace("　", ""); // 移除普通空格和全角空格
        if (!noSpaces.equals(originalName)) {
            possibleNames.add(noSpaces);
        }      
        
        // 去除重复项和空字符串
        return possibleNames.stream()
                .distinct()
                .filter(name -> !name.trim().isEmpty())
                .collect(java.util.stream.Collectors.toList());
    }
    
    
    /**
     * 验证教师姓名格式
     * @param teacherName 教师姓名
     * @return 是否为有效格式
     */
    public boolean isValidTeacherName(String teacherName) {
        if (teacherName == null || teacherName.trim().isEmpty()) {
            return false;
        }
        
        String trimmedName = teacherName.trim();
        
        // 基本长度检查
        if (trimmedName.length() < 1 || trimmedName.length() > 20) {
            return false;
        }
        
        // 检查是否包含有效字符（中文、英文、数字、常见符号）
        if (!trimmedName.matches("[\u4e00-\u9fa5a-zA-Z0-9\s·.]+")) {
            return false;
        }
        
        return true;
    }
}